package com.ymttest.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ymt.core.tool.Logger;


public class GetLog {
	ExecutorService executor = Executors.newFixedThreadPool(1);    
	RemoteShellExecutor2 r2;
	ArrayList<String> logs=new ArrayList<String>();
	String ip;
	String domain;
	public GetLog(String ip,String domain) {
		this.ip=ip;
		this.domain=domain;
	}
	/**
	 * 去ip下的/usr/local/log/{domain} 找文件 默认default.log
	 * 会清空lastlog
	 * @param logfile
	 * @throws IOException
	 */
	public void startListenVm(String logfile,String grep) throws IOException{
		logs=new ArrayList<String>();
		r2=new RemoteShellExecutor2(ip,"ftpuser","1qaz@WSX");
		r2.login();
		InputStream stream=null;
		String cmd="";
		if(logfile!=null&&logfile.length()>0){
			cmd ="tail -f /usr/local/log/"+domain+"/"+logfile;
		}else{
			cmd ="tail -f /usr/local/log/"+domain+"/default.log";
		}
		if(grep!=null&&grep.length()>0){
			cmd +=" | grep --line-buffer "+grep;
		}
		Logger.debug("listen log start:"+cmd);
		stream = r2.getLog(cmd);
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		
		Runnable r1=new Runnable() {
			public void run() {
				while (true) {
					String line=new String();
					try {
						line =br.readLine();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if(null==line){
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							Logger.debug("stop");
						}
					}else{
						logs.add(line);
					}
				}
			}
		};
		executor.submit(r1);
	}
	/**
	 * 结束监听
	 * @throws InterruptedException 
	 */
	public void endListen() throws InterruptedException{
		r2.close();
		executor.shutdownNow();
		Thread.sleep(500);
	}
	/**
	 * 获取log
	 * @return
	 */
	public ArrayList<String> getLastLog(){
		return logs;
	}
}
